package com.shop.loan.proxy;

import com.shop.loan.model.Channel;
import com.shop.loan.service.ChannelService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import xyz.erupt.annotation.fun.DataProxy;
import xyz.erupt.annotation.query.Condition;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Random;


@Service
public class ChannelDataProxy implements DataProxy<Channel> {

    @Value("${sys.urlByH5}")
    private String urlByH5;

    @Resource
    ChannelService channelService;

    @Override
    public void beforeAdd(Channel channel) {
        channel.setCode(getCode());
    }

    @Override
    public String beforeFetch(List<Condition> conditions) {
        List<Long> channelIds = channelService.getChannelIds();
        if(channelIds != null && channelIds.size() > 0){
            String channelIdStr = org.apache.commons.lang3.StringUtils.join(channelIds, ",");
            return  "Channel.id in (" + channelIdStr + ")";
        }
        return null;
    }

    private String getCode() {
        String key = "zbcvbnaasdfghjklqwerty1iop123456789";
        char[] chars = key.toCharArray();
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            code.append(chars[new Random().nextInt(key.length())]);
        }
        return code.toString();
    }


    @Override
    public void afterFetch(Collection<Map<String, Object>> list) {
        for (Map<String, Object> stringObjectMap : list) {
            if (stringObjectMap.containsKey("code")) {
                String param = "code=" + stringObjectMap.get("code");
                String urlLink = urlByH5 + "pagesUser/invite/index?" + param;
                stringObjectMap.put("urlCode", urlLink);

                stringObjectMap.put("url", stringObjectMap.get("urlCode"));
            }
        }
    }
}
